package network;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;

import javax.swing.DefaultListModel;

public class MultiChatServerThread extends Thread {
	MultiChatServer server;
	Socket socket;
	ObjectInputStream receive;
	ObjectOutputStream send;
	boolean tFlag = true;
	ArrayList<Socket> slist;
	ArrayList<String> ulist;
	SocketData sd;
	DefaultListModel<String> dlmt = new DefaultListModel<String>();
	
	//db접속
	String driver = "oracle.jdbc.driver.OracleDriver";
	String url = "jdbc:oracle:thin:@127.0.0.1:1521:xe";
	String db_user = "hr";
	String db_pwd = "hr";
	Connection con;

	
	public MultiChatServerThread(MultiChatServer a, Socket b) {
		this.server=a;
		this.socket=b;

		try {
			Class.forName(driver).newInstance();
			con = DriverManager.getConnection(url, db_user, db_pwd);			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	@Override
	public void run(){
		try{			
			send = new ObjectOutputStream(socket.getOutputStream());
			receive = new ObjectInputStream(socket.getInputStream());			

			while(tFlag){

				
				sd = (SocketData)receive.readObject();	
				InetAddress ia = server.client.getInetAddress();
				if(sd.getCommand().equals("login")){		
					server.clients.put(sd.getUser(), this); // 맵에 유저 아이디 저장.
					
					server.dlm.addElement(sd.getUser());
					sendUserList();

				}else if(sd.getCommand().equals("message")){					
					sendMsg();
					chat_history(sd.getUser(), sd.getMessage());
					
				}else if(sd.getCommand().equals("logout")){
					sendMsg();					
					server.dataSet("접속해제 IP : " + String.valueOf(ia));										
					
					for(int i=server.dlm.size()-1;i>-1;i--){ // list에 중복 업데이트를 방지하기 위한 로직.
						if(server.dlm.getElementAt(i).equals(sd.getUser())){
							server.dlm.remove(i);
						}						
					}
					sendUserList();
					server.clients.remove((sd.getUser()));
					
					tFlag=false;	// while 문 종료를 위한 false;				
				}else if(sd.getCommand().equals("fileTrans")){
					FileServer fs = new FileServer(send);
					fs.setVisible(true);
				}else if(sd.getCommand().equals("serverdown")){
					tFlag=false;
				}
				
				server.dataSet(sd); // 굉장히 중요한 개념. 서버에 있는 dataSet을 부를것이다.
				//sendMsg(sd);
			}
			socket.close(); // 소켓 닫음
			
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	public void sendMsg() { // while 문 안에서 쓰일 메세지 전송, 각 Client에게 메세지 전달.
		//server.clients.put(sd.getUser(), this);
		Set<String> key = server.clients.keySet();
		Iterator<String> it = key.iterator();
		try {
			while(it.hasNext()){
				server.clients.get(it.next()).send.writeObject(sd);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}			
	}
	
	public void sendUserList(){ // sd.setObj 에 dlm add 후 넘기기
		try{		
			Set<String> st = server.clients.keySet();
			Iterator<String> it = st.iterator();						
			server.dataSet("접속자 IP : " + String.valueOf(server.client.getInetAddress()));
			dlmt.clear();
			
			while(it.hasNext()){
				String key = it.next();
				dlmt.addElement(key);				
			}
			sd.setObj(dlmt);
			sendMsg();
			
		}catch(Exception ex){
			
		}
	}	
	public void sendMsg(SocketData sd){
		try{
			int index = server.comboBox.getSelectedIndex();
			if(index>0){
				sd.setIndex(index);
			}
			send.writeObject(sd);
			send.flush();
			server.comboBox.setSelectedIndex(0);
		}catch(Exception ex){
			
		}		
	}
	public void chat_history(String id, String msg){
		String sql = "insert into chat_history values ( sysdate, ?, ? )";
		try{
			
			PreparedStatement pstmt = con.prepareStatement(sql);			
			pstmt.setString(1, id);
			pstmt.setString(2, msg);
			pstmt.executeUpdate();
			
		}catch(Exception ex){
			ex.printStackTrace();
		}
		
		
	}
}












